package com.woniu.inlet.timer;

import com.woniu.outlet.dao.MessagePoMapper;
import com.woniu.outlet.po.MessagePo;
import com.woniu.outlet.po.MessagePoExample;
import com.woniu.utils.MessageStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class MessageTimer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MessagePoMapper messageMapper;

    @Scheduled(fixedRate=10000)
    public void sendMessage(){

        System.out.println("开始工作了");
        //1.查询message表 状态为未发送的消息，而且重复次数大于0
        MessagePoExample example = new MessagePoExample();
        MessagePoExample.Criteria criteria = example.createCriteria();
        //状态为未发送的
        criteria.andStatusNotEqualTo(MessageStatus.SENDED.getStatus());
        criteria.andRetryCountGreaterThan(0);
        List<MessagePo> messages = messageMapper.selectByExample(example);


        for (MessagePo message : messages){
            MessagePostProcessor processor = new MessagePostProcessor() {
                @Override
                public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message1) throws AmqpException {
                    message1.getMessageProperties().setCorrelationId(message.getId().toString());
                    return message1;
                }
            };
            rabbitTemplate.convertAndSend(message.getExchange(),message.getRoutingKey(),
                    message.getMessageContent(),processor,new CorrelationData(message.getId().toString()));

            //次数要 -1
            message.setRetryCount(message.getRetryCount()-1);
            messageMapper.updateByPrimaryKeySelective(message);
        }


    }

}
